package com.v1.video.domain;

import java.io.File;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.UUID;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.nfc.Tag;

import com.google.gson.Gson;
import com.iss.view.common.ToastAlone;
import com.v1.video.Constant;
import com.v1.video.option.db.PersonalCenterUploadDB;
import com.v1.video.util.Logger;
import com.v1.video.util.StreamTool;
import com.v1.video.util.ali.OSSAndroidDemo;

/**
 * 
 * 视频上传时初始化，保存视频信息及上传线程，需要信息从该对象读取
 * 
 * @author Administrator
 *
 */


/*
//上传假数据
        UploadInfo.getInstance().clear();
        UploadInfo.getInstance().setUserName(LoginInfo.getInstance().getUserName());
        UploadInfo.getInstance().setDetail("detail111");
        UploadInfo.getInstance().setPlayNum("0");
        UploadInfo.getInstance().setForward("0");
        UploadInfo.getInstance().setComments("0");
        UploadInfo.getInstance().setCreateTime("2014-5-9 18:00:00.0"); 当前时间注意格式
        UploadInfo.getInstance().startUpload(this, "/mnt/sdcard/V1/HeadLine/Zero/Video/1097758.mp4", "detail111", "12345", "title11", "北京 海淀", "吃饭时");
        
        //
 */

public class UploadInfo extends VideoInfo{
	private static String TAG = "UploadInfo";
	private static UploadInfo instance;
	
	public UploadInfo(){
		
	}
	
	public static UploadInfo getInstance(){
		if(instance == null){
			instance = new UploadInfo();
		}
		return instance;
	}
	
	/**
	 * 清除所有数据
	 * 
	 */
	public void clear(){
		instance = null;
	}
	
	//状态
	/** 上传中 */
	private boolean uploading = false;
	/** 上传数据标识 */
	private boolean sendFileFlag = false;
	
	private Socket socket;
	
	/**
	 * 初始化各种状态，准备上传
	 * 
	 * @param content
	 * @param uri
	 * @param detail
	 * @param related_Video_Id
	 * @param title
	 * @param scenario
	 */
	public void startUpload(Context content, String uri, String detail, String related_Video_Id, String title, String address, String scenario){
		
//		uploading = true;
//		sendFileFlag = true;
////		this.uploadVideo= uri;
////		this.videoFile = new File(uri.toString());
//		this.videoPlayer = MediaPlayer.create(content, Uri.parse(uri));
//		this.fileLength = videoFile.length();
//		
//		/*
//		header = new Header("" + videoFile.length(), detail, "" + videoPlayer.getDuration(), 
//				related_Video_Id, title, LoginInfo.getInstance().getUserId(), videoFile.getName(), 
//				"headerMess", resetUUID(UUID.randomUUID().toString()), address, scenario);
//		*/
//		PersonalCenterUploadDB.getInstance(context).insertUploadInfo(header,context);
//		uploadStart();
		
	}
	
	
	Context context = null;
	/**
	 * 
	 * @param uri 缩图
	 * @param videoFile 视频对象
	 * @param header 
	 */
	public void startUpload(String uri, Header header,Context context) {
	    this.context = context;
		uploading = true;
		sendFileFlag = true;
		
		this.header = header;
		this.header.filePath = uri;
		this.fileLength = Long.valueOf(header.Content_Length);
//		Logger.i(TAG, "fileLength=="+fileLength);
//		this.uploadVideo = uri;
//		this.videoFile = new File(uri.toString());
		
//		this.fileLength = this.videoFile.length();
		setStype("2");
//		PersonalCenterUploadDB.getInstance(context).insertUploadInfo(header,context);
//		uploadStart();//改用阿里云上传了
		new OSSAndroidDemo().main(context,header);
	}
	public void uploadFinish(){
		
	}
	
	//视频信息
	
	/** 上传视频的Uri */
	public String uploadVideo;
	/** 视频文件大小 */
	private long fileLength;
	/** 视频文件对象 */
	public File videoFile;
	/** 视频媒体对象 */
	private MediaPlayer videoPlayer;
	/** 已上传大小 */
	private String uploadedLength;
	/** 视频相关信息 */
	private Header header;	
	/**上传进度*/
	private int progress;
	
	public void uploadStart(){
		
//		new Thread(){
//			
//			public void run(){
//				
//				OutputStream outStream = null;
//				PushbackInputStream inStream = null;
//				RandomAccessFile fileOutStream = null;
//				
//				try {
//					socket = new Socket(Constant.VIDEO_UPLOAD_IP,Constant.VIDEO_UPLOAD_PORT);
//					if(!socket.isConnected()){
//					    ToastAlone.showToast((Activity) context, "网络异常请稍后再试！", 1);					    
//					    clear();
//						return;
//					}
//					
//					//从服务器读取数据
//					Gson gson = new Gson();
//					outStream = socket.getOutputStream();
//					inStream = new PushbackInputStream(socket.getInputStream());
//					String headMsg = gson.toJson(header);
//					headMsg=java.net.URLEncoder.encode(headMsg, "UTF-8");
//					headMsg +="\r\n";
//					outStream.write(headMsg.getBytes());
//    				String response = StreamTool.readLine(inStream);
//    				if(response != null){
//    					response = java.net.URLDecoder.decode(response, "UTF-8");
//    					JSONObject json = new JSONObject(response);
//    					if(json != null && json.getJSONObject("result").getString("code").equals("0")){
//    						
//    						String position = json.getString("Content_Length");
//    						String sourceid = json.getString("sourceid");
//    						
//    						fileOutStream = new RandomAccessFile(videoFile, "r");  
//    	    				fileOutStream.seek(Integer.valueOf(position));
//    	    				byte[] buffer = new byte[1024];  
//    	    				int len = -1;  
//    	    				int length = Integer.valueOf(position);  
//    	    				header.state = "0";
//    	    				
//							while (sendFileFlag && (len = fileOutStream.read(buffer)) != -1) {
//								outStream.write(buffer, 0, len);
//								length += len;
//								setUploadedLength(length);
//								Logger.i(TAG, "fileLength is : " + fileLength
//										+ "   ,upload length is : " + length);
//								Logger.i(TAG, "percent=="+getPercent());
//							}
//							header.state = "1";
//							Header header1 = header;
//							header1.related_Video_Id = header.related_Video_Id1;
//							header1.scenario = header.scenario1;
//							PersonalCenterUploadDB.getInstance(context).updataUploadInfo(header1,context);
//							Logger.i("upload","upload success!!!!");
//    					}else{
//    						Logger.i("upload","response erroe :" + response);
//    						ToastAlone.showToast((Activity) context, "网络异常请稍后再试！", 1);
//    						clear();
//    						Intent i = new Intent("com.v1.video.action.updatafabu");
//    			            context.sendBroadcast(i);
//    					}
//    				}else{
//    					Logger.i("upload","response == null");
//    					clear();
//    					Intent i = new Intent("com.v1.video.action.updatafabu");
//                        context.sendBroadcast(i);
//    				}
//    				  					
//				} /*catch (UnknownHostException e) {
//				    ToastAlone.showToast((Activity) context, "网络错误请稍后再试！", 1);
//				    clear();
//					e.printStackTrace();
//				} catch (IOException e) {
//				    ToastAlone.showToast((Activity) context, "网络错误请稍后再试！", 1);
//				    clear();
//					e.printStackTrace();
//				} catch (JSONException e) {
//				    ToastAlone.showToast((Activity) context, "网络错误请稍后再试！", 1);
//					e.printStackTrace();
//					clear();
//				}*/catch(Exception e){
//				    ToastAlone.showToast((Activity) context, "网络异常请稍后再试！", 1);
//				    e.printStackTrace();
//				    clear();
//				    Intent i = new Intent("com.v1.video.action.updatafabu");
//                    context.sendBroadcast(i);
//				}finally{
//					IOUtils.closeQuietly(fileOutStream);
//					IOUtils.closeQuietly(inStream);
//					IOUtils.closeQuietly(outStream);
//					IOUtils.closeQuietly(socket);
//				}
//				
//				sendFileFlag = false;
//				uploading = false;
//			}
//			
//		}.start();
		
	}	
	
	public void uploadPause(){
		
		sendFileFlag = false;
		
	}
	
	public int getPercent(){
	    if(fileLength <= 0){
	        return -1;
	    }
	    if(uploadedLength == null || uploadedLength.equals("") || uploadedLength.equals("null")){
	        return 0;
	    }
		return (int)(Long.valueOf(uploadedLength) * 100 / fileLength);
	}
	
	//set & get
	
	public void setUploadedLength(int length){
		uploadedLength = Integer.valueOf(length).toString();
	}
	
	public String getUploadedLength(){
		return uploadedLength;
	}
	
	public boolean isUploading() {
		return uploading;
	}
	
	public void setUploading(boolean bool){
		uploading = bool;
	}

	public String getUploadVideo() {
		return uploadVideo;
	}

	public void setUploadVideo(String uploadVideo) {
		this.uploadVideo = uploadVideo;
	}

	public Header getHerder() {
		return header;
	}

	public void setHerder(Header herder) {
		this.header = herder;
	}
	
	//
	
	public static String getUUID(){
		String uuid = UUID.randomUUID().toString();
		Logger.i(TAG, "原始的uuid=="+uuid);
		String str[] = uuid.split("-");
		StringBuffer newStr = new StringBuffer();
		for(String s:str){
			newStr.append(s);
		}
		return newStr.toString();
	}
	
	public int getProgress() {
		return progress;
	}

	public void setProgress(int progress) {
		this.progress = progress;
	}
	
	/**
	 * 上传大小
	 * @return
	 */
	public float getUploadSize(){
		
		float result = 0.0f;
		if(uploadedLength == null || uploadedLength.equals("") || uploadedLength.equals("null")){			
	        return 0;
	    }
		
		result = Float.valueOf(uploadedLength)/1024/1024;
		Logger.i(TAG, "uploadedLength="+uploadedLength+"result="+result);
		String value = result+"";
		if(value.contains(".")){
			int index = value.indexOf(".");
			String value1 = value.substring(index+1);
			if(value1.length() > 2){
				value1 = value1.substring(0, 2);
				String value2 = value.substring(0, index);
				value = value2+"."+value1;
				result = Float.valueOf(value);
			}
		}
		Logger.i(TAG, "uploadedLength="+uploadedLength+"result="+result);
		return result;
	}
	
	/**
	 * 总大小（M）
	 * @return
	 */
	public float getUploadTotalSize(){
		float result = 0.0f;
		if(fileLength <= 0){
		      return 0;
		}
		result = Float.valueOf(fileLength)/1024/1024;
		Logger.i(TAG, "result11111111111="+result);
		String value = result+"";
		if(value.contains(".")){
			int index = value.indexOf(".");
			String value1 = value.substring(index+1);
			if(value1.length() > 2){
				value1 = value1.substring(0, 2);
				String value2 = value.substring(0, index);
				value = value2+"."+value1;
				result = Float.valueOf(value);
			}
		}
		Logger.i(TAG, "fileLength="+fileLength+"result="+result);
		return result;
	}
	
}
